<template>
  <div class="flex-y">
    <div class="flex-x al-start" id="form-related-catalog">
      <biz-form-remote-select
        ref="product"
        :field="field"
        :input-disabled="disabled ? true : false"
        v-model="comValue"
        :value-key="field.setting.searchValueKey || 'id'"
        :remote-method="remoteMethod"
        @input="update"
        :cleared="true"
        :multiple="field.multiple"
        :placeholder="placeholder || $t('common.base.inputKeywordToSearch2')"
      >
        <div
          class="related-task-option"
          slot="optionvalue"
          slot-scope="{ option }"
        >
          <div
            class="related-task-option-desc"
            v-if="field && field.setting && field.setting.searchShowList"
          >
            <div
              class="flex-x al-s"
              v-for="(item, index) in field.setting.searchShowList"
              :key="index"
            >
              <!-- label如果传空则不展示label -->
              <div v-if="item.label">{{ item.label }}：</div>
              <div v-if="item.hasOwnProperty('returnValue')">
                {{ item.returnValue(option) }}
              </div>
              <div v-else>{{ option[item.key] }}</div>
            </div>
            <!-- <p
              
            >
              <span>{{ option[item.key] }}</span>
            </p> -->
          </div>
        </div>
      </biz-form-remote-select>
      <el-button
        v-show="
          comValue.length &&
            field &&
            field.setting &&
            field.setting.searchToView
        "
        class="mar-l-10"
        @click="preview"
      >{{ $t('common.base.view') }}</el-button
      >
    </div>
    <div
      class="tips-card"
      v-show="
        comValue.length &&
          field.setting &&
          field.setting.returnShowType == 'cards'
      "
    >
      <div
        class="tips-card-item"
        v-for="(item, index) in comValue"
        :key="index"
      >
        <div
          class="flex-x al-s"
          v-for="(items, indexs) in field.setting.searchShowList"
          :key="indexs"
        >
          <div>{{ items.label }}：</div>
          <div v-if="items.hasOwnProperty('returnValue')" class="flex-1">
            {{ items.returnValue(item) }}
          </div>
          <div v-else class="flex-1">{{ item[items.key] }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/** api */

/** mixin */
import FormMixin from '@src/component/form/mixin/form';

import { productSearchCatalog } from '@src/modules/guideForNewUser/initData.js';

import { isEmpty, isObject, isArray, isUndefined } from '@src/util/type';

import _ from 'lodash';

/**
 * @des 通用联想搜索搜索页面配置参数(pc端组件是 formType = 'relatedCatalog'的 继承组件)
 * @param {Promise} searchApi 搜索所调用的api
 * @param {String} searchValueKey 搜索关联的主键key
 * @param {String} searchShowKey 搜索所用来展示的主key
 * @param {Array} searchShowList 搜索列表需要展示的数据
 * @param {Object} searchParams 搜索函数需要携带的参数
 * @param {Arrary} returnValueKey 后端接口需要拼接的参数集合(理论上需要除去当前的filedName 特殊情况特殊对待)
 * @param {Function} searchParamsFnc 搜索函数需要携带的参数函数形式
 * @param {String} returnShowType 参数回显展示的形式 tips 标签形式展示searchShowKey所关联的数据 cards 卡片形式以searchShowList所包括的参数展示
 * @param {Boolean} isMultiple pc端组件参数为field的 multiple
 * @param {String} searchReturn list返回参数不是code返回体
 * @param {Boolean} attributeKeep 保存attribute结构
 */

const defaultListSetting = {
  searchValueKey: 'id',
  searchShowKey: 'name',
  searchShowList: [{ key: 'name', label: '名称', isSystem: 1 }],
  returnShowType: 'tips',
  isMultiple: false,
  attributeKeep: false,
};

export default {
  name: 'usual-select',
  mixins: [FormMixin],
  props: {
    value: {
      type: Array | String,
      default: () => [],
    },
  },
  data() {
    return {
      comValue: [],

      page: 1,
      pageSize: 20,
    };
  },
  watch: {
    value(val) {
      this.init(val);
    },
  },
  mounted() {
    this.init(this.value);
  },
  methods: {
    init(val) {
      let res_ = [];
      if (val && isArray(val) && val.length > 0) {
        res_ = _.cloneDeep(val);
      } else if (isObject(val) && val.hasOwnProperty('id')) {
        res_ = [val];
      }
      res_ = this.filterArr(res_);
      if (JSON.stringify(res_) != JSON.stringify(this.comValue)) {
        this.comValue = res_;
      }
    },
    remoteMethod(params) {
      if (this.field.justGuide) return Promise.resolve(productSearchCatalog);
      let { keyword, pageNum, pageSize } = params;
      params = {
        page: pageNum,
        pageSize: 50,
        pageNum,
        keyword,
        keyWord: keyword,
      };
      // 如果传了usePageNum，代表分页参数为pageNum
      if (this.field.setting && this.field.setting.usePageNum) {
        params.pageNum = pageNum;
        delete params.page;
      }
      let httpFn;
      try {
        httpFn = this.field.setting && this.field.setting.searchApi;
        if (this.field.setting && this.field.setting.searchParams) {
          params = { ...params, ...this.field.setting.searchParams };
        }
        if (this.field.setting && this.field.setting.searchParamsFnc) {
          params = { ...params, ...this.field.setting.searchParamsFnc() };
        }
      } catch (error) {
        console.warn(error, 'error try catch');
        return Promise.resolve();
      }

      return httpFn(params)
        .then((res) => {
          let fail = false;
          let result_ = {};
          if (this.field.setting && this.field.setting.searchReturn == 'old') {
            fail = !res || !res.list;
            if (fail) return;
            result_ = res;
          } else {
            fail = !res || !res.result || !res.result.list;
            if (fail) return;
            result_ = res.result;
          }

          let key = this.field?.setting?.searchShowKey || 'id';
          result_.list = result_.list.map((item) => {
            // 扁平化attribute
            if (
              !this.field.setting.hasOwnProperty('attributeKeep')
              && item.hasOwnProperty('attribute')
            ) {
              item = { ...item, ...item.attribute };
              delete item.attribute;
            }
            return Object.freeze({
              label: item[key],
              ...item,
            });
          });

          return result_;
        })
        .catch((e) => console.error(e));
    },
    update(newValue) {
      let res_;
      res_ = this.filterArr(newValue);
      this.inputForValue(res_);
    },
    /**
     * @des 根据表单结构提供的数据过滤数据
     */
    filterArr(arr) {
      try {
        let res_ = _.cloneDeep(arr);
        let key_ = this.field?.setting?.searchValueKey || 'id';
        let key_show = this.field?.setting?.searchShowKey || 'id';
        res_ = res_.map((item) => {
          // let obj_ = {};
          // 已经是前端转换后的数据
          if (item.hasOwnProperty('mainValueKey')) {
            // 针对移动端用不到label这个属性做处理
            item['label'] = item[key_show];
            return item;
          }
          // this.field.setting.searchShowList.map((item_) => {
          //   obj_[item_.key] = item[item_.key];
          // });
          item['label'] = item[key_show];
          item['mainValueKey'] = item[key_];
          // 扁平化attribute
          if (
            !this.field.setting.hasOwnProperty('attributeKeep')
            && item.hasOwnProperty('attribute')
          ) {
            item = { ...item, ...item.attribute };
            delete item.attribute;
          }
          return item;
        });
        return res_;
      } catch (error) {
        console.warn(error, 'error try catch');
        return [];
      }
    },
    preview() {
      if (!this.comValue.length) return;
      try {
        this.field.setting.searchToView(this.comValue);
      } catch (error) {
        console.warn(error, 'error try catch');
      }

      // 快捷跳转
      // this.$platform.openTab({
      //   id: 'productV2_catalog_edit',
      //   title: '新建设备类型',
      //   url: `/productV2/catalog/edit?id=${this.comValue[0].parentId}&tableId=${
      //     this.comValue[0].id
      //   }`,
      //   reload: true,
      //   close: true,
      // });
    },
    /**
     * @des 针对部分搜索只能提供id的数据做快速搜索
     * 处于精准性必须提供id主键进行搜索查询
     */
    fasterChoose(ids = []) {
      let params_ = {
        page: 1,
        pageSize: 50,
        pageNum: 1,
        keyword: '',
        keyWord: '',
        ids: ids.join(','),
      };
      this.remoteMethod(params_).then((res) => {
        if (res) {
          let arr_;
          let res_ = [];
          if (res.code == 0) {
            arr_ = res.data || res.result;
          } else if (res.list) {
            arr_ = res.list;
          }
          res_ = arr_ && arr_.filter((item) => ids.includes(item.id));
          this.update(res_);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.related-task-option {
  font-size: 13px;
}
.tips-card {
  width: 100%;

  .tips-card-item {
    border-radius: 4px;
    background: #f0f2f5;
    margin-top: 8px;
    padding: 8px;
    font-size: 12px;
  }
}
</style>
<style lang="scss">
#form-related-catalog {
  .el-input__suffix {
    display: none;
  }
  .biz-form-remote-select {
    position: relative;
    .biz-form-remote-select-clear {
      top: 0;
      bottom: 0;
      margin: auto;
      display: flex;
      align-items: center;
      .el-icon-error{
        color: #8c8c8c!important;
        font-size: 12px;
      }
    }
  }
}
</style>
